//
//  QuizSpreadHeadView.m
//  SpreadViewDemo
//
//  Created by Tianlong on 2018/1/26.
//  Copyright © 2018年 Tianlong. All rights reserved.
//

#import "QuizSpreadHeadView.h"
#import "Masonry.h"

#define BottomM 104 // 背景距离底部的间距
#define UIMaxH 500  //UI设计最高展开高度为500

@interface QuizSpreadHeadView ()
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgBottomM;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *spreadBtnBottomM;
@property (weak, nonatomic) UIView *inView;
@property (weak, nonatomic) UIImageView *dullBg;
@property (assign, nonatomic) BOOL isSpread;
@property (assign, nonatomic) BOOL isRecorded;
@property (assign, nonatomic) CGFloat maxH;
@property (assign, nonatomic) CGFloat contentRealH;
// 记录下未展开时view的高度
@property (assign, nonatomic) CGFloat selfNormalH;
// 展开时的最大高度
@property (assign, nonatomic) CGFloat spreadMaxH;
@end

@implementation QuizSpreadHeadView

+ (instancetype)spreadHeadInView:(UIView *)inView contentRealHeight:(CGFloat)realH spreadMaxHeight:(CGFloat)maxHeight{
    
    QuizSpreadHeadView *spv = [QuizSpreadHeadView loadFromNib];
    spv.inView = inView;
    spv.contentRealH = realH;
    spv.spreadMaxH = maxHeight;
    
    // 磨砂背景
    UIImageView *dullBg = [[UIImageView alloc] init];
    dullBg.alpha = 0;
    dullBg.backgroundColor = [UIColor blackColor];
    spv.dullBg = dullBg;
    [inView addSubview:dullBg];
    [dullBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(inView);
    }];
    
    return spv;
}

- (IBAction)spread:(id)sender {
    
    __weak typeof(self)ws   = self;
    
    if (!self.isRecorded) {
        self.selfNormalH = self.height;
        self.maxH = self.spreadMaxH > 0 ? (self.spreadMaxH > UIMaxH ? UIMaxH: self.spreadMaxH) : UIMaxH;
        if ([UIScreen mainScreen].bounds.size.width == 320) {
            self.maxH = self.inView.height-self.y-BottomM;
        }
        self.isRecorded = YES;
    }
    
    CGFloat duration = .25;
    CGFloat finalRealH = self.contentRealH > self.maxH ? self.maxH : self.contentRealH;
    CGFloat spreadH = finalRealH > self.selfNormalH ? finalRealH - self.selfNormalH : 0;
    
    if(!self.isSpread){
        [UIView animateWithDuration:duration animations:^{
            ws.height += spreadH;
            ws.bgBottomM.constant -= spreadH;
            ws.spreadBtnBottomM.constant += spreadH;
            ws.dullBg.alpha = 0.4;
            [ws layoutIfNeeded];
        }];
    }else{
        [UIView animateWithDuration:duration animations:^{
            ws.height -= spreadH;
            ws.bgBottomM.constant += spreadH;
            ws.spreadBtnBottomM.constant -= spreadH;
            ws.dullBg.alpha = 0;
            [ws layoutIfNeeded];
        }];
    }
    self.isSpread = !self.isSpread;
}

@end
